﻿using Microsoft.Practices.ServiceLocation;
using Microsoft.Practices.Unity;
using MuddyBoots.GreenlightQC.DataService;
using MuddyBoots.GreenlightQC.Mobile.Persistence;
using MuddyBoots.GreenlightQC.Mobile.UI.Helpers;
using MuddyBoots.GreenlightQC.Mobile.UI.ViewModel;
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MuddyBoots.GreenlightQC.Mobile.UI
{
    public sealed class BootStrapper : IDisposable
    {
        IUnityContainer container;
         
        public BootStrapper()
        {
            container = new UnityContainer();
            this.ConfigureContainer();
            var serviceLocator = new UnityServiceLocator(container);
            ServiceLocator.SetLocatorProvider(() => serviceLocator);
        }

        public T Get<T>()
        {
            return container.Resolve<T>();
        }

        public void Dispose()
        {
            if (container == null)
            {
                return;
            }

            container.Dispose();
            container = null;
        }

        private void ConfigureContainer()
        {
            container.RegisterType<Logger>(new ContainerControlledLifetimeManager(), new InjectionFactory((t, s, c) =>
            {
                return LogManager.GetLogger(t.GetType().Name);
            }));

            var log = container.Resolve<Logger>();
            log.Debug("BootStrapper: Configuring container started...");

            // This is done as a singleton becuase of the way the multi-lingual support is done by Infralution.Localization.Wpf, everytime the culture
            // is changed it will rebind the view model locator and therefore request the view model be re-created...
            container.RegisterType<MainWindowViewModel>(new ContainerControlledLifetimeManager());

            container.RegisterType<IGreenlightQCMobile, GreenlightQCMobileMock>();
            container.RegisterType<IDatabaseEntities, DatabaseEntities>();

            log.Debug("BootStrapper: Configuring container completed...");
        }
    }
}
